#include "../include/cmd.h"

//mkdir and rm 
// mkdir，传入要创建的文件夹名char *，返回是否成功
// 默认创建的权限为644
int mkdir_command(int fd, cmd_t *cmd)
{
    if(cmd->argSize != 1){
        printf("error arguments.\n");
        return 1;
    }
    int ret = mkdir(cmd->args[0].arg, 0777);
    return ret + 1;
}

// rm，删除文件，传入文件的地址，返回是否成功
int rm_command(int fd,cmd_t* cmd)
{    
    char* buf=cmd->args[0].arg;
    //判断删除文件还是文件夹
    struct stat st;
    int ret;
    ret=stat(buf,&st);
    if(ret==-1)
    {
        send(fd,&ret,4,MSG_WAITALL);
        return -1;
    }
    if((st.st_mode&S_IFMT)==S_IFDIR)
    {
        ret=rm_dir(buf);
        send(fd,&ret,4,MSG_WAITALL);
        return ret;
    }
    //处理文件
    ret=rm_file(buf);
    //返回结果
    send(fd,&ret,4,MSG_WAITALL);
    return ret;
}

int rm_file(char* filename)        
{
    int ret=remove(filename);
    return ret;
}

int rm_dir(char* dirname)
{
    int ret=0;
    DIR* pdir=opendir(dirname);
    if(pdir==NULL)
    {
        return -1;
    }
    struct dirent *pdirent;
    while((pdirent=readdir(pdir))!=NULL)
    {
        char *name=pdirent->d_name;
        if((!strcmp(name,"."))||(!strcmp(name,"..")))
        {
            continue;
        }
        char dirfilename[512]={0};
        sprintf(dirfilename,"%s/%s",dirname,pdirent->d_name);
        if(pdirent->d_type==DT_DIR)
        {
            rm_dir(dirfilename);
        }
        else
        {                          
            rm_file(dirfilename);
        }
    }
    rmdir(dirname);
    closedir(pdir);
    return 0;
}
